package com.pub.util;


/* Title:		
 *
 * Project:     current
 *
 * @ Link: 		http://...
 *
 * @ Email:		ivan_ling@mezimedia.com
 *
 * @ Copyright: Copyright (c) 2008 mezimedia
 *
 * @ Author 	Ivan.ling
 *
 * @ Version 	1.0
 
 * @ last change time 2008-04-28	
 */

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

public class HttpUtils
{
	public static enum METHOD {GET, POST};
  
	
	
	/* main method
	 * @ param 	String[] : nothing param.
	 */
	public static void main(String args[])
	{
		
		HttpURLConnection connSetURL;
		try {
			connSetURL = HttpUtils.getHttpConnURL("http://purgecache.mezimedia.com/cgi-bin/purgeAkamaiCache.pl", HttpUtils.METHOD.POST);
			HttpUtils.sendPost(connSetURL, "emailaddress=be@mezimedia.com&urls=http://images.smarter.com/product_image_b/2/32/1232.jpg\nhttp://images.smarter.com/product_image_s/2/32/1232.jpg");
			System.out.print("out === " + HttpUtils.getContent(connSetURL));
			//;;;
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		

	}
	
	public static HttpURLConnection getHttpConnURL(String urlAddr) throws IOException
    {
    	HttpURLConnection conn = null;
    	
        URL url = new URL(urlAddr);
      	conn = (HttpURLConnection)url.openConnection();
      	conn.setRequestMethod(HttpUtils.METHOD.GET.name());
        conn.setDoInput(true);
        conn.setDoOutput(true);

        return conn;
    }  

	public static HttpURLConnection getHttpConnURL(String urlAddr, int timeout) throws IOException
    {
    	HttpURLConnection conn = null;
    	
        URL url = new URL(urlAddr);
      	conn = (HttpURLConnection)url.openConnection();
      	
      	conn.setConnectTimeout(timeout);
      	conn.setRequestMethod(HttpUtils.METHOD.GET.name());
        conn.setDoInput(true);
        conn.setDoOutput(true);

        return conn;
    }
	
	public static HttpURLConnection getHttpConnURL(String urlAddr, METHOD method) throws IOException
    {
    	HttpURLConnection conn = null;
    	
        URL url = new URL(urlAddr);
      	conn = (HttpURLConnection)url.openConnection();
      	conn.setRequestMethod(method.name());
        conn.setDoInput(true);
        conn.setDoOutput(true);

        return conn;
    }  
	
	public static HttpURLConnection getHttpConnURL(String urlAddr, Proxy proxy) throws IOException
    {
    	HttpURLConnection conn = null;
    	
        URL url = new URL(urlAddr);
      	conn = (HttpURLConnection)url.openConnection(proxy);
       
      	conn.setDoInput(true);
        conn.setDoOutput(true);

        return conn;
    }  
	
	public static URLConnection getConnURL(String urlAddr) throws IOException
    {
    	URLConnection conn = null;
    	
        URL url = new URL(urlAddr);
      	conn = (URLConnection)url.openConnection();

      	conn.setDoInput(true);
        conn.setDoOutput(true);

        return conn;
    }
	
	public static URLConnection getConnURL(String urlAddr, Proxy proxy) throws IOException
    {
    	URLConnection conn = null;
    	
        URL url = new URL(urlAddr);
      	conn = (URLConnection)url.openConnection(proxy);

      	conn.setDoInput(true);
        conn.setDoOutput(true);

        return conn;
    }
	
	public static HttpsURLConnection getHttpsConnURL(String urlAddr, Proxy proxy) throws IOException
    {
    	HttpsURLConnection conn = null;
    	
        trustServer();
        
		URL url = new URL(urlAddr);
      	conn = (HttpsURLConnection)url.openConnection(proxy);
        conn.setDoInput(true);
        conn.setDoOutput(true);
       
        return conn;
	    
    }
	
	public static HttpsURLConnection getHttpsConnURL(String urlAddr, METHOD method) throws IOException
    {
    	HttpsURLConnection conn = null;
    	
        trustServer();
        
		URL url = new URL(urlAddr);
      	conn = (HttpsURLConnection)url.openConnection();
      	conn.setRequestMethod(method.name());
        conn.setDoInput(true);
        conn.setDoOutput(true);
       
        return conn;
	    
    }

   public static void sendPost(HttpURLConnection ucConn, String strQuery) throws IOException
   {  
       if(strQuery == null)
    	   return;
       
	   PrintWriter output;
       
       output = new PrintWriter(ucConn.getOutputStream());
       output.print(strQuery);
       output.flush();
       output.close();
   }

    public static String getContent(HttpURLConnection ucConn)
    {  
        String line;
        StringBuilder sbCache = new StringBuilder(1000);
        try {  
        	ucConn.connect();  
            BufferedReader in = new BufferedReader(new InputStreamReader(ucConn.getInputStream()));
            
            while ((line = in.readLine()) != null) {  
            	sbCache.append(line);
            	sbCache.append("\n");  
            }
            in.close();  
        } catch (IOException ex) {
            ex.printStackTrace();  
        }
        
        return sbCache.toString();
    }
    
    public static String getContent(URLConnection ucConn)
    {  
        String line;
        StringBuilder sbCache = new StringBuilder(1000);
        try {  
        	ucConn.connect();  
        	
//        	System.out.println("-----get connSetURL = " + ucConn.getHeaderFields().toString());
//        	
            BufferedReader in = new BufferedReader(new InputStreamReader(ucConn.getInputStream()));
            
            while ((line = in.readLine()) != null) {  
            	sbCache.append(line);
            	sbCache.append("\n");  
            }
            in.close();  
        } catch (IOException ex) {
            ex.printStackTrace(); 
            
            return null;
        }
        
        return sbCache.toString();
    }
    
    public static String getContent(HttpURLConnection ucConn, String charsetName)
    {  
        String line;
        StringBuilder sbCache = new StringBuilder(1000);
        try {  
        	ucConn.connect();  
            BufferedReader in = new BufferedReader(new InputStreamReader(ucConn.getInputStream(), charsetName));
            
            while ((line = in.readLine()) != null) {  
            	sbCache.append(line);
            	sbCache.append("\n");  
            }
            in.close();  
        } catch (IOException ex) {
            ex.printStackTrace();  
        }
        
        return sbCache.toString();
    }
    
    public static String getContent(HttpsURLConnection ucConn)
    {  
        String line;
        StringBuilder sbCache = new StringBuilder(1000);
        try {  
        	ucConn.connect();  
            BufferedReader in = new BufferedReader(new InputStreamReader(ucConn.getInputStream()));
            
            while ((line = in.readLine()) != null) {  
            	sbCache.append(line);
            	sbCache.append("\n");  
            }
            in.close();  
        } catch (IOException ex) {
            ex.printStackTrace();  
        }
        
        return sbCache.toString();
    }
    
    public static byte[] getByteContent(HttpURLConnection ucConn) throws IOException
    {  
    	InputStream is = ucConn.getInputStream();
    	ByteArrayOutputStream baOS = new ByteArrayOutputStream();
    	
    	int ch;
    	
    	while ((ch = is.read()) != -1) {  
    		baOS.write(ch);
    	}
    	
    	byte[] btReturn = baOS.toByteArray();
    	baOS.close();
    	
    	return btReturn;
    }
    
    public String getContent(String url, Map<String, String> mapRequestProperty) throws IOException
    {
    	HttpURLConnection httpURLConn;
    	
    	URL queryURL = new URL(url);
    	
    	httpURLConn = (HttpURLConnection)queryURL.openConnection();
    	
    	for(Entry<String, String> entry : mapRequestProperty.entrySet()){
    		httpURLConn.setRequestProperty(entry.getKey(), entry.getValue());	
    	}
    	
		httpURLConn.setRequestMethod(HttpUtils.METHOD.POST.name());
		
		httpURLConn.setConnectTimeout(120000);
		httpURLConn.setReadTimeout(300000);
		
		httpURLConn.setInstanceFollowRedirects(false);
    	httpURLConn.setDoInput(true);
    	httpURLConn.setDoOutput(true);
    	
    	HttpUtils.sendPost(httpURLConn, "");

		return HttpUtils.getContent(httpURLConn);
    }
    
    public byte[] getByteContent(String url, Map<String, String> mapRequestProperty) throws IOException
    {
    	HttpURLConnection httpURLConn;
    	
    	URL queryURL = new URL(url);
    	
    	httpURLConn = (HttpURLConnection)queryURL.openConnection();
    	
    	for(Entry<String, String> entry : mapRequestProperty.entrySet()){
    		httpURLConn.setRequestProperty(entry.getKey(), entry.getValue());	
    	}
    	
		httpURLConn.setRequestMethod(HttpUtils.METHOD.POST.name());
		
		httpURLConn.setConnectTimeout(120000);
		httpURLConn.setReadTimeout(300000);
		
		httpURLConn.setInstanceFollowRedirects(false);
    	httpURLConn.setDoInput(true);
    	httpURLConn.setDoOutput(true);
    	
    	HttpUtils.sendPost(httpURLConn, "");

		return HttpUtils.getByteContent(httpURLConn);
    }
    
    /*-- rewrite three method of X509TrustManager, credit sertificate of server --*/
    protected static X509TrustManager xTrustManager = new X509TrustManager()
    {
	    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
	    {
	    }

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
		{
		}

		public X509Certificate[] getAcceptedIssuers()
		{
			return null;
		}
    };

    /*-- credit host name --*/
    protected static HostnameVerifier hostNameVerifier = new HostnameVerifier()
    {
    	public boolean verify(String hostname, SSLSession session) {
    		return true;
    	}
    };

    /**
     * creidt host, ignore host name and sertificate for create connection , avoid to config sertificate in client
     */
    public static void trustServer() 
    {
    	SSLContext sslContext = null;
		try {
		    sslContext = SSLContext.getInstance("TLS");
		    X509TrustManager[] xtmArray = new X509TrustManager[] { xTrustManager };
		    sslContext.init(null, xtmArray, new java.security.SecureRandom());
		} catch (GeneralSecurityException e) {
		    e.printStackTrace();
		}

		if (sslContext != null) {
		    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
		}
		HttpsURLConnection.setDefaultHostnameVerifier(hostNameVerifier);
    }
}